home *** CD-ROM | disk | FTP | other *** search
/ Workbench Add-On / Workbench Add-On - Volume 1.iso / BBS-Archive / Dev / gcc-2.6.3-bin.lha / GNU / info / cpp.info-2 (.txt) < prev    next >
GNU Info File  |  1995-03-30  |  40KB  |  729 lines

  1. This is Info file cpp.info, produced by Makeinfo-1.55 from the input
  2. file cpp.texi.
  3.    This file documents the GNU C Preprocessor.
  4.    Copyright 1987, 1989, 1991, 1992, 1993, 1994 Free Software
  5. Foundation, Inc.
  6.    Permission is granted to make and distribute verbatim copies of this
  7. manual provided the copyright notice and this permission notice are
  8. preserved on all copies.
  9.    Permission is granted to copy and distribute modified versions of
  10. this manual under the conditions for verbatim copying, provided also
  11. that the entire resulting derived work is distributed under the terms
  12. of a permission notice identical to this one.
  13.    Permission is granted to copy and distribute translations of this
  14. manual into another language, under the above conditions for modified
  15. versions.
  16. File: cpp.info,  Node: Macro Parentheses,  Next: Swallow Semicolon,  Prev: Misnesting,  Up: Macro Pitfalls
  17. Unintended Grouping of Arithmetic
  18. .................................
  19.    You may have noticed that in most of the macro definition examples
  20. shown above, each occurrence of a macro argument name had parentheses
  21. around it.  In addition, another pair of parentheses usually surround
  22. the entire macro definition.  Here is why it is best to write macros
  23. that way.
  24.    Suppose you define a macro as follows,
  25.      #define ceil_div(x, y) (x + y - 1) / y
  26. whose purpose is to divide, rounding up.  (One use for this operation is
  27. to compute how many `int' objects are needed to hold a certain number
  28. of `char' objects.)  Then suppose it is used as follows:
  29.      a = ceil_div (b & c, sizeof (int));
  30. This expands into
  31.      a = (b & c + sizeof (int) - 1) / sizeof (int);
  32. which does not do what is intended.  The operator-precedence rules of C
  33. make it equivalent to this:
  34.      a = (b & (c + sizeof (int) - 1)) / sizeof (int);
  35. But what we want is this:
  36.      a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
  37. Defining the macro as
  38.      #define ceil_div(x, y) ((x) + (y) - 1) / (y)
  39. provides the desired result.
  40.    However, unintended grouping can result in another way.  Consider
  41. `sizeof ceil_div(1, 2)'.  That has the appearance of a C expression
  42. that would compute the size of the type of `ceil_div (1, 2)', but in
  43. fact it means something very different.  Here is what it expands to:
  44.      sizeof ((1) + (2) - 1) / (2)
  45. This would take the size of an integer and divide it by two.  The
  46. precedence rules have put the division outside the `sizeof' when it was
  47. intended to be inside.
  48.    Parentheses around the entire macro definition can prevent such
  49. problems.  Here, then, is the recommended way to define `ceil_div':
  50.      #define ceil_div(x, y) (((x) + (y) - 1) / (y))
  51. File: cpp.info,  Node: Swallow Semicolon,  Next: Side Effects,  Prev: Macro Parentheses,  Up: Macro Pitfalls
  52. Swallowing the Semicolon
  53. ........................
  54.    Often it is desirable to define a macro that expands into a compound
  55. statement.  Consider, for example, the following macro, that advances a
  56. pointer (the argument `p' says where to find it) across whitespace
  57. characters:
  58.      #define SKIP_SPACES (p, limit)  \
  59.      { register char *lim = (limit); \
  60.        while (p != lim) {            \
  61.          if (*p++ != ' ') {          \
  62.            p--; break; }}}
  63. Here Backslash-Newline is used to split the macro definition, which must
  64. be a single line, so that it resembles the way such C code would be
  65. laid out if not part of a macro definition.
  66.    A call to this macro might be `SKIP_SPACES (p, lim)'.  Strictly
  67. speaking, the call expands to a compound statement, which is a complete
  68. statement with no need for a semicolon to end it.  But it looks like a
  69. function call.  So it minimizes confusion if you can use it like a
  70. function call, writing a semicolon afterward, as in `SKIP_SPACES (p,
  71. lim);'
  72.    But this can cause trouble before `else' statements, because the
  73. semicolon is actually a null statement.  Suppose you write
  74.      if (*p != 0)
  75.        SKIP_SPACES (p, lim);
  76.      else ...
  77. The presence of two statements--the compound statement and a null
  78. statement--in between the `if' condition and the `else' makes invalid C
  79. code.
  80.    The definition of the macro `SKIP_SPACES' can be altered to solve
  81. this problem, using a `do ... while' statement.  Here is how:
  82.      #define SKIP_SPACES (p, limit)     \
  83.      do { register char *lim = (limit); \
  84.           while (p != lim) {            \
  85.             if (*p++ != ' ') {          \
  86.               p--; break; }}}           \
  87.      while (0)
  88.    Now `SKIP_SPACES (p, lim);' expands into
  89.      do {...} while (0);
  90. which is one statement.
  91. File: cpp.info,  Node: Side Effects,  Next: Self-Reference,  Prev: Swallow Semicolon,  Up: Macro Pitfalls
  92. Duplication of Side Effects
  93. ...........................
  94.    Many C programs define a macro `min', for "minimum", like this:
  95.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  96.    When you use this macro with an argument containing a side effect,
  97. as shown here,
  98.      next = min (x + y, foo (z));
  99. it expands as follows:
  100.      next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
  101. where `x + y' has been substituted for `X' and `foo (z)' for `Y'.
  102.    The function `foo' is used only once in the statement as it appears
  103. in the program, but the expression `foo (z)' has been substituted twice
  104. into the macro expansion.  As a result, `foo' might be called two times
  105. when the statement is executed.  If it has side effects or if it takes
  106. a long time to compute, the results might not be what you intended.  We
  107. say that `min' is an "unsafe" macro.
  108.    The best solution to this problem is to define `min' in a way that
  109. computes the value of `foo (z)' only once.  The C language offers no
  110. standard way to do this, but it can be done with GNU C extensions as
  111. follows:
  112.      #define min(X, Y)                     \
  113.      ({ typeof (X) __x = (X), __y = (Y);   \
  114.         (__x < __y) ? __x : __y; })
  115.    If you do not wish to use GNU C extensions, the only solution is to
  116. be careful when *using* the macro `min'.  For example, you can
  117. calculate the value of `foo (z)', save it in a variable, and use that
  118. variable in `min':
  119.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  120.      ...
  121.      {
  122.        int tem = foo (z);
  123.        next = min (x + y, tem);
  124.      }
  125. (where we assume that `foo' returns type `int').
  126. File: cpp.info,  Node: Self-Reference,  Next: Argument Prescan,  Prev: Side Effects,  Up: Macro Pitfalls
  127. Self-Referential Macros
  128. .......................
  129.    A "self-referential" macro is one whose name appears in its
  130. definition.  A special feature of ANSI Standard C is that the
  131. self-reference is not considered a macro call.  It is passed into the
  132. preprocessor output unchanged.
  133.    Let's consider an example:
  134.      #define foo (4 + foo)
  135. where `foo' is also a variable in your program.
  136.    Following the ordinary rules, each reference to `foo' will expand
  137. into `(4 + foo)'; then this will be rescanned and will expand into `(4
  138. + (4 + foo))'; and so on until it causes a fatal error (memory full) in
  139. the preprocessor.
  140.    However, the special rule about self-reference cuts this process
  141. short after one step, at `(4 + foo)'.  Therefore, this macro definition
  142. has the possibly useful effect of causing the program to add 4 to the
  143. value of `foo' wherever `foo' is referred to.
  144.    In most cases, it is a bad idea to take advantage of this feature.  A
  145. person reading the program who sees that `foo' is a variable will not
  146. expect that it is a macro as well.  The reader will come across the
  147. identifier `foo' in the program and think its value should be that of
  148. the variable `foo', whereas in fact the value is four greater.
  149.    The special rule for self-reference applies also to "indirect"
  150. self-reference.  This is the case where a macro X expands to use a
  151. macro `y', and the expansion of `y' refers to the macro `x'.  The
  152. resulting reference to `x' comes indirectly from the expansion of `x',
  153. so it is a self-reference and is not further expanded.  Thus, after
  154.      #define x (4 + y)
  155.      #define y (2 * x)
  156. `x' would expand into `(4 + (2 * x))'.  Clear?
  157.    But suppose `y' is used elsewhere, not from the definition of `x'.
  158. Then the use of `x' in the expansion of `y' is not a self-reference
  159. because `x' is not "in progress".  So it does expand.  However, the
  160. expansion of `x' contains a reference to `y', and that is an indirect
  161. self-reference now because `y' is "in progress".  The result is that
  162. `y' expands to `(2 * (4 + y))'.
  163.    It is not clear that this behavior would ever be useful, but it is
  164. specified by the ANSI C standard, so you may need to understand it.
  165. File: cpp.info,  Node: Argument Prescan,  Next: Cascaded Macros,  Prev: Self-Reference,  Up: Macro Pitfalls
  166. Separate Expansion of Macro Arguments
  167. .....................................
  168.    We have explained that the expansion of a macro, including the
  169. substituted actual arguments, is scanned over again for macro calls to
  170. be expanded.
  171.    What really happens is more subtle: first each actual argument text
  172. is scanned separately for macro calls.  Then the results of this are
  173. substituted into the macro body to produce the macro expansion, and the
  174. macro expansion is scanned again for macros to expand.
  175.    The result is that the actual arguments are scanned *twice* to expand
  176. macro calls in them.
  177.    Most of the time, this has no effect.  If the actual argument
  178. contained any macro calls, they are expanded during the first scan.
  179. The result therefore contains no macro calls, so the second scan does
  180. not change it.  If the actual argument were substituted as given, with
  181. no prescan, the single remaining scan would find the same macro calls
  182. and produce the same results.
  183.    You might expect the double scan to change the results when a
  184. self-referential macro is used in an actual argument of another macro
  185. (*note Self-Reference::.): the self-referential macro would be expanded
  186. once in the first scan, and a second time in the second scan.  But this
  187. is not what happens.  The self-references that do not expand in the
  188. first scan are marked so that they will not expand in the second scan
  189. either.
  190.    The prescan is not done when an argument is stringified or
  191. concatenated.  Thus,
  192.      #define str(s) #s
  193.      #define foo 4
  194.      str (foo)
  195. expands to `"foo"'.  Once more, prescan has been prevented from having
  196. any noticeable effect.
  197.    More precisely, stringification and concatenation use the argument as
  198. written, in un-prescanned form.  The same actual argument would be used
  199. in prescanned form if it is substituted elsewhere without
  200. stringification or concatenation.
  201.      #define str(s) #s lose(s)
  202.      #define foo 4
  203.      str (foo)
  204.    expands to `"foo" lose(4)'.
  205.    You might now ask, "Why mention the prescan, if it makes no
  206. difference?  And why not skip it and make the preprocessor faster?"
  207. The answer is that the prescan does make a difference in three special
  208. cases:
  209.    * Nested calls to a macro.
  210.    * Macros that call other macros that stringify or concatenate.
  211.    * Macros whose expansions contain unshielded commas.
  212.    We say that "nested" calls to a macro occur when a macro's actual
  213. argument contains a call to that very macro.  For example, if `f' is a
  214. macro that expects one argument, `f (f (1))' is a nested pair of calls
  215. to `f'.  The desired expansion is made by expanding `f (1)' and
  216. substituting that into the definition of `f'.  The prescan causes the
  217. expected result to happen.  Without the prescan, `f (1)' itself would
  218. be substituted as an actual argument, and the inner use of `f' would
  219. appear during the main scan as an indirect self-reference and would not
  220. be expanded.  Here, the prescan cancels an undesirable side effect (in
  221. the medical, not computational, sense of the term) of the special rule
  222. for self-referential macros.
  223.    But prescan causes trouble in certain other cases of nested macro
  224. calls.  Here is an example:
  225.      #define foo  a,b
  226.      #define bar(x) lose(x)
  227.      #define lose(x) (1 + (x))
  228.      
  229.      bar(foo)
  230. We would like `bar(foo)' to turn into `(1 + (foo))', which would then
  231. turn into `(1 + (a,b))'.  But instead, `bar(foo)' expands into
  232. `lose(a,b)', and you get an error because `lose' requires a single
  233. argument.  In this case, the problem is easily solved by the same
  234. parentheses that ought to be used to prevent misnesting of arithmetic
  235. operations:
  236.      #define foo (a,b)
  237.      #define bar(x) lose((x))
  238.    The problem is more serious when the operands of the macro are not
  239. expressions; for example, when they are statements.  Then parentheses
  240. are unacceptable because they would make for invalid C code:
  241.      #define foo { int a, b; ... }
  242. In GNU C you can shield the commas using the `({...})' construct which
  243. turns a compound statement into an expression:
  244.      #define foo ({ int a, b; ... })
  245.    Or you can rewrite the macro definition to avoid such commas:
  246.      #define foo { int a; int b; ... }
  247.    There is also one case where prescan is useful.  It is possible to
  248. use prescan to expand an argument and then stringify it--if you use two
  249. levels of macros.  Let's add a new macro `xstr' to the example shown
  250. above:
  251.      #define xstr(s) str(s)
  252.      #define str(s) #s
  253.      #define foo 4
  254.      xstr (foo)
  255.    This expands into `"4"', not `"foo"'.  The reason for the difference
  256. is that the argument of `xstr' is expanded at prescan (because `xstr'
  257. does not specify stringification or concatenation of the argument).
  258. The result of prescan then forms the actual argument for `str'.  `str'
  259. uses its argument without prescan because it performs stringification;
  260. but it cannot prevent or undo the prescanning already done by `xstr'.
  261. File: cpp.info,  Node: Cascaded Macros,  Next: Newlines in Args,  Prev: Argument Prescan,  Up: Macro Pitfalls
  262. Cascaded Use of Macros
  263. ......................
  264.    A "cascade" of macros is when one macro's body contains a reference
  265. to another macro.  This is very common practice.  For example,
  266.      #define BUFSIZE 1020
  267.      #define TABLESIZE BUFSIZE
  268.    This is not at all the same as defining `TABLESIZE' to be `1020'.
  269. The `#define' for `TABLESIZE' uses exactly the body you specify--in
  270. this case, `BUFSIZE'--and does not check to see whether it too is the
  271. name of a macro.
  272.    It's only when you *use* `TABLESIZE' that the result of its expansion
  273. is checked for more macro names.
  274.    This makes a difference if you change the definition of `BUFSIZE' at
  275. some point in the source file.  `TABLESIZE', defined as shown, will
  276. always expand using the definition of `BUFSIZE' that is currently in
  277. effect:
  278.      #define BUFSIZE 1020
  279.      #define TABLESIZE BUFSIZE
  280.      #undef BUFSIZE
  281.      #define BUFSIZE 37
  282. Now `TABLESIZE' expands (in two stages) to `37'.  (The `#undef' is to
  283. prevent any warning about the nontrivial redefinition of `BUFSIZE'.)
  284. File: cpp.info,  Node: Newlines in Args,  Prev: Cascaded Macros,  Up: Macro Pitfalls
  285. Newlines in Macro Arguments
  286. ---------------------------
  287.    Traditional macro processing carries forward all newlines in macro
  288. arguments into the expansion of the macro.  This means that, if some of
  289. the arguments are substituted more than once, or not at all, or out of
  290. order, newlines can be duplicated, lost, or moved around within the
  291. expansion.  If the expansion consists of multiple statements, then the
  292. effect is to distort the line numbers of some of these statements.  The
  293. result can be incorrect line numbers, in error messages or displayed in
  294. a debugger.
  295.    The GNU C preprocessor operating in ANSI C mode adjusts appropriately
  296. for multiple use of an argument--the first use expands all the
  297. newlines, and subsequent uses of the same argument produce no newlines.
  298. But even in this mode, it can produce incorrect line numbering if
  299. arguments are used out of order, or not used at all.
  300.    Here is an example illustrating this problem:
  301.      #define ignore_second_arg(a,b,c) a; c
  302.      
  303.      ignore_second_arg (foo (),
  304.                         ignored (),
  305.                         syntax error);
  306. The syntax error triggered by the tokens `syntax error' results in an
  307. error message citing line four, even though the statement text comes
  308. from line five.
  309. File: cpp.info,  Node: Conditionals,  Next: Combining Sources,  Prev: Macros,  Up: Top
  310. Conditionals
  311. ============
  312.    In a macro processor, a "conditional" is a command that allows a part
  313. of the program to be ignored during compilation, on some conditions.
  314. In the C preprocessor, a conditional can test either an arithmetic
  315. expression or whether a name is defined as a macro.
  316.    A conditional in the C preprocessor resembles in some ways an `if'
  317. statement in C, but it is important to understand the difference between
  318. them.  The condition in an `if' statement is tested during the execution
  319. of your program.  Its purpose is to allow your program to behave
  320. differently from run to run, depending on the data it is operating on.
  321. The condition in a preprocessor conditional command is tested when your
  322. program is compiled.  Its purpose is to allow different code to be
  323. included in the program depending on the situation at the time of
  324. compilation.
  325. * Menu:
  326. * Uses: Conditional Uses.       What conditionals are for.
  327. * Syntax: Conditional Syntax.   How conditionals are written.
  328. * Deletion: Deleted Code.       Making code into a comment.
  329. * Macros: Conditionals-Macros.  Why conditionals are used with macros.
  330. * Assertions::                How and why to use assertions.
  331. * Errors: #error Command.       Detecting inconsistent compilation parameters.
  332. File: cpp.info,  Node: Conditional Uses,  Next: Conditional Syntax,  Up: Conditionals
  333. Why Conditionals are Used
  334. -------------------------
  335.    Generally there are three kinds of reason to use a conditional.
  336.    * A program may need to use different code depending on the machine
  337.      or operating system it is to run on.  In some cases the code for
  338.      one operating system may be erroneous on another operating system;
  339.      for example, it might refer to library routines that do not exist
  340.      on the other system.  When this happens, it is not enough to avoid
  341.      executing the invalid code: merely having it in the program makes
  342.      it impossible to link the program and run it.  With a preprocessor
  343.      conditional, the offending code can be effectively excised from
  344.      the program when it is not valid.
  345.    * You may want to be able to compile the same source file into two
  346.      different programs.  Sometimes the difference between the programs
  347.      is that one makes frequent time-consuming consistency checks on its
  348.      intermediate data, or prints the values of those data for
  349.      debugging, while the other does not.
  350.    * A conditional whose condition is always false is a good way to
  351.      exclude code from the program but keep it as a sort of comment for
  352.      future reference.
  353.    Most simple programs that are intended to run on only one machine
  354. will not need to use preprocessor conditionals.
  355. File: cpp.info,  Node: Conditional Syntax,  Next: Deleted Code,  Prev: Conditional Uses,  Up: Conditionals
  356. Syntax of Conditionals
  357. ----------------------
  358.    A conditional in the C preprocessor begins with a "conditional
  359. command": `#if', `#ifdef' or `#ifndef'.  *Note Conditionals-Macros::,
  360. for information on `#ifdef' and `#ifndef'; only `#if' is explained here.
  361. * Menu:
  362. * If: #if Command.     Basic conditionals using `#if' and `#endif'.
  363. * Else: #else Command. Including some text if the condition fails.
  364. * Elif: #elif Command. Testing several alternative possibilities.
  365. File: cpp.info,  Node: #if Command,  Next: #else Command,  Up: Conditional Syntax
  366. The `#if' Command
  367. .................
  368.    The `#if' command in its simplest form consists of
  369.      #if EXPRESSION
  370.      CONTROLLED TEXT
  371.      #endif /* EXPRESSION */
  372.    The comment following the `#endif' is not required, but it is a good
  373. practice because it helps people match the `#endif' to the
  374. corresponding `#if'.  Such comments should always be used, except in
  375. short conditionals that are not nested.  In fact, you can put anything
  376. at all after the `#endif' and it will be ignored by the GNU C
  377. preprocessor, but only comments are acceptable in ANSI Standard C.
  378.    EXPRESSION is a C expression of integer type, subject to stringent
  379. restrictions.  It may contain
  380.    * Integer constants, which are all regarded as `long' or `unsigned
  381.      long'.
  382.    * Character constants, which are interpreted according to the
  383.      character set and conventions of the machine and operating system
  384.      on which the preprocessor is running.  The GNU C preprocessor uses
  385.      the C data type `char' for these character constants; therefore,
  386.      whether some character codes are negative is determined by the C
  387.      compiler used to compile the preprocessor.  If it treats `char' as
  388.      signed, then character codes large enough to set the sign bit will
  389.      be considered negative; otherwise, no character code is considered
  390.      negative.
  391.    * Arithmetic operators for addition, subtraction, multiplication,
  392.      division, bitwise operations, shifts, comparisons, and logical
  393.      operations (`&&' and `||').
  394.    * Identifiers that are not macros, which are all treated as zero(!).
  395.    * Macro calls.  All macro calls in the expression are expanded before
  396.      actual computation of the expression's value begins.
  397.    Note that `sizeof' operators and `enum'-type values are not allowed.
  398. `enum'-type values, like all other identifiers that are not taken as
  399. macro calls and expanded, are treated as zero.
  400.    The CONTROLLED TEXT inside of a conditional can include preprocessor
  401. commands.  Then the commands inside the conditional are obeyed only if
  402. that branch of the conditional succeeds.  The text can also contain
  403. other conditional groups.  However, the `#if' and `#endif' commands
  404. must balance.
  405. File: cpp.info,  Node: #else Command,  Next: #elif Command,  Prev: #if Command,  Up: Conditional Syntax
  406. The `#else' Command
  407. ...................
  408.    The `#else' command can be added to a conditional to provide
  409. alternative text to be used if the condition is false.  This is what it
  410. looks like:
  411.      #if EXPRESSION
  412.      TEXT-IF-TRUE
  413.      #else /* Not EXPRESSION */
  414.      TEXT-IF-FALSE
  415.      #endif /* Not EXPRESSION */
  416.    If EXPRESSION is nonzero, and thus the TEXT-IF-TRUE is active, then
  417. `#else' acts like a failing conditional and the TEXT-IF-FALSE is
  418. ignored.  Contrariwise, if the `#if' conditional fails, the
  419. TEXT-IF-FALSE is considered included.
  420. File: cpp.info,  Node: #elif Command,  Prev: #else Command,  Up: Conditional Syntax
  421. The `#elif' Command
  422. ...................
  423.    One common case of nested conditionals is used to check for more
  424. than two possible alternatives.  For example, you might have
  425.      #if X == 1
  426.      ...
  427.      #else /* X != 1 */
  428.      #if X == 2
  429.      ...
  430.      #else /* X != 2 */
  431.      ...
  432.      #endif /* X != 2 */
  433.      #endif /* X != 1 */
  434.    Another conditional command, `#elif', allows this to be abbreviated
  435. as follows:
  436.      #if X == 1
  437.      ...
  438.      #elif X == 2
  439.      ...
  440.      #else /* X != 2 and X != 1*/
  441.      ...
  442.      #endif /* X != 2 and X != 1*/
  443.    `#elif' stands for "else if".  Like `#else', it goes in the middle
  444. of a `#if'-`#endif' pair and subdivides it; it does not require a
  445. matching `#endif' of its own.  Like `#if', the `#elif' command includes
  446. an expression to be tested.
  447.    The text following the `#elif' is processed only if the original
  448. `#if'-condition failed and the `#elif' condition succeeds.  More than
  449. one `#elif' can go in the same `#if'-`#endif' group.  Then the text
  450. after each `#elif' is processed only if the `#elif' condition succeeds
  451. after the original `#if' and any previous `#elif' commands within it
  452. have failed.  `#else' is equivalent to `#elif 1', and `#else' is
  453. allowed after any number of `#elif' commands, but `#elif' may not follow
  454. `#else'.
  455. File: cpp.info,  Node: Deleted Code,  Next: Conditionals-Macros,  Prev: Conditional Syntax,  Up: Conditionals
  456. Keeping Deleted Code for Future Reference
  457. -----------------------------------------
  458.    If you replace or delete a part of the program but want to keep the
  459. old code around as a comment for future reference, the easy way to do
  460. this is to put `#if 0' before it and `#endif' after it.  This is better
  461. than using comment delimiters `/*' and `*/' since those won't work if
  462. the code already contains comments (C comments do not nest).
  463.    This works even if the code being turned off contains conditionals,
  464. but they must be entire conditionals (balanced `#if' and `#endif').
  465.    Conversely, do not use `#if 0' for comments which are not C code.
  466. Use the comment delimiters `/*' and `*/' instead.  The interior of `#if
  467. 0' must consist of complete tokens; in particular, singlequote
  468. characters must balance.  But comments often contain unbalanced
  469. singlequote characters (known in English as apostrophes).  These
  470. confuse `#if 0'.  They do not confuse `/*'.
  471. File: cpp.info,  Node: Conditionals-Macros,  Next: Assertions,  Prev: Deleted Code,  Up: Conditionals
  472. Conditionals and Macros
  473. -----------------------
  474.    Conditionals are useful in connection with macros or assertions,
  475. because those are the only ways that an expression's value can vary
  476. from one compilation to another.  A `#if' command whose expression uses
  477. no macros or assertions is equivalent to `#if 1' or `#if 0'; you might
  478. as well determine which one, by computing the value of the expression
  479. yourself, and then simplify the program.
  480.    For example, here is a conditional that tests the expression
  481. `BUFSIZE == 1020', where `BUFSIZE' must be a macro.
  482.      #if BUFSIZE == 1020
  483.        printf ("Large buffers!\n");
  484.      #endif /* BUFSIZE is large */
  485.    (Programmers often wish they could test the size of a variable or
  486. data type in `#if', but this does not work.  The preprocessor does not
  487. understand `sizeof', or typedef names, or even the type keywords such
  488. as `int'.)
  489.    The special operator `defined' is used in `#if' expressions to test
  490. whether a certain name is defined as a macro.  Either `defined NAME' or
  491. `defined (NAME)' is an expression whose value is 1 if NAME is defined
  492. as macro at the current point in the program, and 0 otherwise.  For the
  493. `defined' operator it makes no difference what the definition of the
  494. macro is; all that matters is whether there is a definition.  Thus, for
  495. example,
  496.      #if defined (vax) || defined (ns16000)
  497. would succeed if either of the names `vax' and `ns16000' is defined as
  498. a macro.  You can test the same condition using assertions (*note
  499. Assertions::.), like this:
  500.      #if #cpu (vax) || #cpu (ns16000)
  501.    If a macro is defined and later undefined with `#undef', subsequent
  502. use of the `defined' operator returns 0, because the name is no longer
  503. defined.  If the macro is defined again with another `#define',
  504. `defined' will recommence returning 1.
  505.    Conditionals that test whether just one name is defined are very
  506. common, so there are two special short conditional commands for this
  507. case.
  508. `#ifdef NAME'
  509.      is equivalent to `#if defined (NAME)'.
  510. `#ifndef NAME'
  511.      is equivalent to `#if ! defined (NAME)'.
  512.    Macro definitions can vary between compilations for several reasons.
  513.    * Some macros are predefined on each kind of machine.  For example,
  514.      on a Vax, the name `vax' is a predefined macro.  On other
  515.      machines, it would not be defined.
  516.    * Many more macros are defined by system header files.  Different
  517.      systems and machines define different macros, or give them
  518.      different values.  It is useful to test these macros with
  519.      conditionals to avoid using a system feature on a machine where it
  520.      is not implemented.
  521.    * Macros are a common way of allowing users to customize a program
  522.      for different machines or applications.  For example, the macro
  523.      `BUFSIZE' might be defined in a configuration file for your
  524.      program that is included as a header file in each source file.  You
  525.      would use `BUFSIZE' in a preprocessor conditional in order to
  526.      generate different code depending on the chosen configuration.
  527.    * Macros can be defined or undefined with `-D' and `-U' command
  528.      options when you compile the program.  You can arrange to compile
  529.      the same source file into two different programs by choosing a
  530.      macro name to specify which program you want, writing conditionals
  531.      to test whether or how this macro is defined, and then controlling
  532.      the state of the macro with compiler command options.  *Note
  533.      Invocation::.
  534.    Assertions are usually predefined, but can be defined with
  535. preprocessor commands or command-line options.
  536. File: cpp.info,  Node: Assertions,  Next: #error Command,  Prev: Conditionals-Macros,  Up: Conditionals
  537. Assertions
  538. ----------
  539.    "Assertions" are a more systematic alternative to macros in writing
  540. conditionals to test what sort of computer or system the compiled
  541. program will run on.  Assertions are usually predefined, but you can
  542. define them with preprocessor commands or command-line options.
  543.    The macros traditionally used to describe the type of target are not
  544. classified in any way according to which question they answer; they may
  545. indicate a hardware architecture, a particular hardware model, an
  546. operating system, a particular version of an operating system, or
  547. specific configuration options.  These are jumbled together in a single
  548. namespace.  In contrast, each assertion consists of a named question and
  549. an answer.  The question is usually called the "predicate".  An
  550. assertion looks like this:
  551.      #PREDICATE (ANSWER)
  552. You must use a properly formed identifier for PREDICATE.  The value of
  553. ANSWER can be any sequence of words; all characters are significant
  554. except for leading and trailing whitespace, and differences in internal
  555. whitespace sequences are ignored.  Thus, `x + y' is different from
  556. `x+y' but equivalent to `x + y'.  `)' is not allowed in an answer.
  557.    Here is a conditional to test whether the answer ANSWER is asserted
  558. for the predicate PREDICATE:
  559.      #if #PREDICATE (ANSWER)
  560. There may be more than one answer asserted for a given predicate.  If
  561. you omit the answer, you can test whether *any* answer is asserted for
  562. PREDICATE:
  563.      #if #PREDICATE
  564.    Most of the time, the assertions you test will be predefined
  565. assertions.  GNU C provides three predefined predicates: `system',
  566. `cpu', and `machine'.  `system' is for assertions about the type of
  567. software, `cpu' describes the type of computer architecture, and
  568. `machine' gives more information about the computer.  For example, on a
  569. GNU system, the following assertions would be true:
  570.      #system (gnu)
  571.      #system (mach)
  572.      #system (mach 3)
  573.      #system (mach 3.SUBVERSION)
  574.      #system (hurd)
  575.      #system (hurd VERSION)
  576. and perhaps others.  The alternatives with more or less version
  577. information let you ask more or less detailed questions about the type
  578. of system software.
  579.    On a Unix system, you would find `#system (unix)' and perhaps one of:
  580. `#system (aix)', `#system (bsd)', `#system (hpux)', `#system (lynx)',
  581. `#system (mach)', `#system (posix)', `#system (svr3)', `#system
  582. (svr4)', or `#system (xpg4)' with possible version numbers following.
  583.    Other values for `system' are `#system (mvs)' and `#system (vms)'.
  584.    *Portability note:* Many Unix C compilers provide only one answer
  585. for the `system' assertion: `#system (unix)', if they support
  586. assertions at all.  This is less than useful.
  587.    An assertion with a multi-word answer is completely different from
  588. several assertions with individual single-word answers.  For example,
  589. the presence of `system (mach 3.0)' does not mean that `system (3.0)'
  590. is true.  It also does not directly imply `system (mach)', but in GNU
  591. C, that last will normally be asserted as well.
  592.    The current list of possible assertion values for `cpu' is: `#cpu
  593. (a29k)', `#cpu (alpha)', `#cpu (arm)', `#cpu (clipper)', `#cpu
  594. (convex)', `#cpu (elxsi)', `#cpu (tron)', `#cpu (h8300)', `#cpu
  595. (i370)', `#cpu (i386)', `#cpu (i860)', `#cpu (i960)', `#cpu (m68k)',
  596. `#cpu (m88k)', `#cpu (mips)', `#cpu (ns32k)', `#cpu (hppa)', `#cpu
  597. (pyr)', `#cpu (ibm032)', `#cpu (rs6000)', `#cpu (sh)', `#cpu (sparc)',
  598. `#cpu (spur)', `#cpu (tahoe)', `#cpu (vax)', `#cpu (we32000)'.
  599.    You can create assertions within a C program using `#assert', like
  600. this:
  601.      #assert PREDICATE (ANSWER)
  602. (Note the absence of a `#' before PREDICATE.)
  603.    Each time you do this, you assert a new true answer for PREDICATE.
  604. Asserting one answer does not invalidate previously asserted answers;
  605. they all remain true.  The only way to remove an assertion is with
  606. `#unassert'.  `#unassert' has the same syntax as `#assert'.  You can
  607. also remove all assertions about PREDICATE like this:
  608.      #unassert PREDICATE
  609.    You can also add or cancel assertions using command options when you
  610. run `gcc' or `cpp'.  *Note Invocation::.
  611. File: cpp.info,  Node: #error Command,  Prev: Assertions,  Up: Conditionals
  612. The `#error' and `#warning' Commands
  613. ------------------------------------
  614.    The command `#error' causes the preprocessor to report a fatal
  615. error.  The rest of the line that follows `#error' is used as the error
  616. message.
  617.    You would use `#error' inside of a conditional that detects a
  618. combination of parameters which you know the program does not properly
  619. support.  For example, if you know that the program will not run
  620. properly on a Vax, you might write
  621.      #ifdef __vax__
  622.      #error Won't work on Vaxen.  See comments at get_last_object.
  623.      #endif
  624. *Note Nonstandard Predefined::, for why this works.
  625.    If you have several configuration parameters that must be set up by
  626. the installation in a consistent way, you can use conditionals to detect
  627. an inconsistency and report it with `#error'.  For example,
  628.      #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
  629.          || HASH_TABLE_SIZE % 5 == 0
  630.      #error HASH_TABLE_SIZE should not be divisible by a small prime
  631.      #endif
  632.    The command `#warning' is like the command `#error', but causes the
  633. preprocessor to issue a warning and continue preprocessing.  The rest of
  634. the line that follows `#warning' is used as the warning message.
  635.    You might use `#warning' in obsolete header files, with a message
  636. directing the user to the header file which should be used instead.
  637. File: cpp.info,  Node: Combining Sources,  Next: Other Commands,  Prev: Conditionals,  Up: Top
  638. Combining Source Files
  639. ======================
  640.    One of the jobs of the C preprocessor is to inform the C compiler of
  641. where each line of C code came from: which source file and which line
  642. number.
  643.    C code can come from multiple source files if you use `#include';
  644. both `#include' and the use of conditionals and macros can cause the
  645. line number of a line in the preprocessor output to be different from
  646. the line's number in the original source file.  You will appreciate the
  647. value of making both the C compiler (in error messages) and symbolic
  648. debuggers such as GDB use the line numbers in your source file.
  649.    The C preprocessor builds on this feature by offering a command by
  650. which you can control the feature explicitly.  This is useful when a
  651. file for input to the C preprocessor is the output from another program
  652. such as the `bison' parser generator, which operates on another file
  653. that is the true source file.  Parts of the output from `bison' are
  654. generated from scratch, other parts come from a standard parser file.
  655. The rest are copied nearly verbatim from the source file, but their
  656. line numbers in the `bison' output are not the same as their original
  657. line numbers.  Naturally you would like compiler error messages and
  658. symbolic debuggers to know the original source file and line number of
  659. each line in the `bison' input.
  660.    `bison' arranges this by writing `#line' commands into the output
  661. file.  `#line' is a command that specifies the original line number and
  662. source file name for subsequent input in the current preprocessor input
  663. file.  `#line' has three variants:
  664. `#line LINENUM'
  665.      Here LINENUM is a decimal integer constant.  This specifies that
  666.      the line number of the following line of input, in its original
  667.      source file, was LINENUM.
  668. `#line LINENUM FILENAME'
  669.      Here LINENUM is a decimal integer constant and FILENAME is a
  670.      string constant.  This specifies that the following line of input
  671.      came originally from source file FILENAME and its line number there
  672.      was LINENUM.  Keep in mind that FILENAME is not just a file name;
  673.      it is surrounded by doublequote characters so that it looks like a
  674.      string constant.
  675. `#line ANYTHING ELSE'
  676.      ANYTHING ELSE is checked for macro calls, which are expanded.  The
  677.      result should be a decimal integer constant followed optionally by
  678.      a string constant, as described above.
  679.    `#line' commands alter the results of the `__FILE__' and `__LINE__'
  680. predefined macros from that point on.  *Note Standard Predefined::.
  681.    The output of the preprocessor (which is the input for the rest of
  682. the compiler) contains commands that look much like `#line' commands.
  683. They start with just `#' instead of `#line', but this is followed by a
  684. line number and file name as in `#line'.  *Note Output::.
  685. File: cpp.info,  Node: Other Commands,  Next: Output,  Prev: Combining Sources,  Up: Top
  686. Miscellaneous Preprocessor Commands
  687. ===================================
  688.    This section describes three additional preprocessor commands.  They
  689. are not very useful, but are mentioned for completeness.
  690.    The "null command" consists of a `#' followed by a Newline, with
  691. only whitespace (including comments) in between.  A null command is
  692. understood as a preprocessor command but has no effect on the
  693. preprocessor output.  The primary significance of the existence of the
  694. null command is that an input line consisting of just a `#' will
  695. produce no output, rather than a line of output containing just a `#'.
  696. Supposedly some old C programs contain such lines.
  697.    The ANSI standard specifies that the `#pragma' command has an
  698. arbitrary, implementation-defined effect.  In the GNU C preprocessor,
  699. `#pragma' commands are not used, except for `#pragma once' (*note
  700. Once-Only::.).  However, they are left in the preprocessor output, so
  701. they are available to the compilation pass.
  702.    The `#ident' command is supported for compatibility with certain
  703. other systems.  It is followed by a line of text.  On some systems, the
  704. text is copied into a special place in the object file; on most systems,
  705. the text is ignored and this command has no effect.  Typically `#ident'
  706. is only used in header files supplied with those systems where it is
  707. meaningful.
  708. File: cpp.info,  Node: Output,  Next: Invocation,  Prev: Other Commands,  Up: Top
  709. C Preprocessor Output
  710. =====================
  711.    The output from the C preprocessor looks much like the input, except
  712. that all preprocessor command lines have been replaced with blank lines
  713. and all comments with spaces.  Whitespace within a line is not altered;
  714. however, a space is inserted after the expansions of most macro calls.
  715.    Source file name and line number information is conveyed by lines of
  716. the form
  717.      # LINENUM FILENAME FLAGS
  718. which are inserted as needed into the middle of the input (but never
  719. within a string or character constant).  Such a line means that the
  720. following line originated in file FILENAME at line LINENUM.
  721.    After the file name comes zero or more flags, which are `1', `2' or
  722. `3'.  If there are multiple flags, spaces separate them.  Here is what
  723. the flags mean:
  724.      This indicates the start of a new file.
  725.      This indicates returning to a file (after having included another
  726.      file).
  727.      This indicates that the following text comes from a system header
  728.      file, so certain warnings should be suppressed.
  729.